
#include <stdio.h>
#include <string.h>
#include <driver/spi_master.h>
#include "../__generated/glue_spi.h"

spi_device_handle_t spiDevHdl;

int halSpiInit(i32 spiBus, i32 clkSpeed, i32 miso, i32 mosi,
                 i32 clk)
{
    esp_err_t ret;
    spi_bus_config_t buscfg = {
        .miso_io_num = miso,
        .mosi_io_num = mosi,
        .sclk_io_num = clk,
        .quadwp_io_num = -1,
        .quadhd_io_num = -1,
        .max_transfer_sz = 0};

    spi_device_interface_config_t devcfg = {
        .clock_speed_hz = clkSpeed,
        .mode = 0,
        .spics_io_num = -1,
        .queue_size = 7,
    };

    

    ret = spi_bus_initialize(HSPI_HOST, &buscfg, 1);
    ret = spi_bus_add_device(HSPI_HOST, &devcfg, &spiDevHdl);
    return ret;
}

int halSpiWrite(i32 spiBus, JS_BUFFER buf, i32 len)
{
    esp_err_t ret;
    spi_transaction_t t;
    memset(&t, 0, sizeof(t));
    t.tx_buffer = buf.buf;
    t.length = 8 * len;
    ret = spi_device_polling_transmit(spiDevHdl, &t);
    return ret;
}

int halSpiWriteBits(i32 spiBus, u32 val, i32 bits) {
    esp_err_t ret;
    spi_transaction_t t;
    memset(&t, 0, sizeof(t));
    memcpy(t.tx_data, &val, sizeof(u32));
    t.flags |= SPI_TRANS_USE_TXDATA;
    t.length = bits;
    ret = spi_device_polling_transmit(spiDevHdl, &t);
    return ret;
}

int halSpiXfer(i32 spiBus, JS_BUFFER buf, i32 len, i32 rxlen)
{
    esp_err_t ret;
    spi_transaction_t t;
    memset(&t, 0, sizeof(t));
    t.tx_buffer = buf.buf;
    t.length = 8 * len;
    t.rxlength = 8 * rxlen;
    ret = spi_device_polling_transmit(spiDevHdl, &t);
    return ret;
}




